package com.centaline.androidsalesblog.fragments;


import android.content.Intent;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.android.volley.VolleyError;
import com.bumptech.glide.BitmapTypeRequest;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.mine.CollectionActivity;
import com.centaline.androidsalesblog.activities.mine.ContactActivity;
import com.centaline.androidsalesblog.activities.mine.FootPrintActivity;
import com.centaline.androidsalesblog.activities.mine.LoanCalcActivity;
import com.centaline.androidsalesblog.activities.mine.LoginActivity;
import com.centaline.androidsalesblog.activities.mine.MyActivityActivity;
import com.centaline.androidsalesblog.activities.mine.MyProfileActivity;
import com.centaline.androidsalesblog.activities.mine.OpinionActivity;
import com.centaline.androidsalesblog.activities.mine.SettingsActivity;
import com.centaline.androidsalesblog.activities.mine.SettingsNickNameActivity;
import com.centaline.androidsalesblog.activities.mine.SysMsgListActivity;
import com.centaline.androidsalesblog.activities.mine.TaxCalcActivity;
import com.centaline.androidsalesblog.api.usercenter.UserBookingListApi;
import com.centaline.androidsalesblog.base.BaseFragment;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.events.MineInfoUpdate;
import com.centaline.androidsalesblog.events.UserOperate;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.CollectInfoListRo;
import com.centaline.androidsalesblog.model.responseobject.UserBookListRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.rx.request.RxRequest;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.glide.RoundImageViewTarget;
import com.centanet.framework.interfaces.IResponseListener;
import com.trello.rxlifecycle.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 我的
 */
public class MineFragment extends BaseFragment implements View.OnClickListener {

    private Button btn_login;
    private AppCompatTextView atv_user_name;//用户名
    private ImageView img_user;//用户头像

    private LinearLayout ll_footprint;//足迹
    private AppCompatTextView atv_footprint_number;//足迹数量
    private LinearLayout ll_collection;//收藏
    private AppCompatTextView atv_collection_number;//收藏数量
    private LinearLayout ll_activity;//活动
    private AppCompatTextView atv_activity_number;//活动数量
    private RelativeLayout rl_contact;//最近联系人
    private RelativeLayout rl_loan_calculator;//房贷计算器
    private RelativeLayout rl_tax_calculator;//税费计算器
    private RelativeLayout rl_settings_opinion;//意见反馈
    private RelativeLayout rl_share;//分享
    private RelativeLayout rl_setting;//设置

    private BitmapTypeRequest<String> mBitmapTypeRequest;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void findViews(View view) {
        btn_login = (Button) view.findViewById(R.id.btn_login);
        atv_user_name = (AppCompatTextView) view.findViewById(R.id.atv_user_name);
        img_user = (ImageView) view.findViewById(R.id.img_user);
        ll_footprint = (LinearLayout) view.findViewById(R.id.ll_footprint);
        atv_footprint_number = (AppCompatTextView) view.findViewById(R.id.atv_footprint_number);
        ll_collection = (LinearLayout) view.findViewById(R.id.ll_collection);
        atv_collection_number = (AppCompatTextView) view.findViewById(R.id.atv_collection_number);
        ll_activity = (LinearLayout) view.findViewById(R.id.ll_activity);
        atv_activity_number = (AppCompatTextView) view.findViewById(R.id.atv_activity_number);
        rl_contact = (RelativeLayout) view.findViewById(R.id.rl_contact);
        rl_loan_calculator = (RelativeLayout) view.findViewById(R.id.rl_loan_calculator);
        rl_tax_calculator = (RelativeLayout) view.findViewById(R.id.rl_tax_calculator);
        rl_settings_opinion = (RelativeLayout) view.findViewById(R.id.rl_settings_opinion);
        rl_share = (RelativeLayout) view.findViewById(R.id.rl_share);
        rl_setting = (RelativeLayout) view.findViewById(R.id.rl_setting);
    }

    @Override
    protected void initView() {
        btn_login.setOnClickListener(this);
        atv_user_name.setOnClickListener(this);
        img_user.setOnClickListener(this);
        ll_footprint.setOnClickListener(this);
        ll_collection.setOnClickListener(this);
        ll_activity.setOnClickListener(this);
        rl_contact.setOnClickListener(this);
        rl_loan_calculator.setOnClickListener(this);
        rl_tax_calculator.setOnClickListener(this);
        rl_settings_opinion.setOnClickListener(this);
        rl_share.setOnClickListener(this);
        rl_setting.setOnClickListener(this);
        mBitmapTypeRequest = GlideLoad.initRound(this);
        EventBus.getDefault().register(this);
        setData();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void refreshUi() {
        setData();
    }

    private void setData() {
        setUserInfo();
        fpHistoryCount();
    }

    /**
     * 设置用户信息
     */
    private void setUserInfo() {
        if (AppConstant.IsLogin) {
            RxDataBase.getUser()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(this.<UserDo>bindUntilEvent(FragmentEvent.DESTROY))
                    .subscribe(new Action1<UserDo>() {
                        @Override
                        public void call(UserDo userDo) {
                            if (userDo == null) {
                                btn_login.setVisibility(View.VISIBLE);
                                atv_user_name.setText("");
                                img_user.setImageResource(R.drawable.ic_mine_icon);
                                atv_collection_number.setText("0");
                                atv_activity_number.setText("0");
                            } else {
                                btn_login.setVisibility(View.GONE);
                                atv_user_name.setText(TextUtils.isEmpty(userDo.getNickName()) ? "点击设置" : userDo.getNickName());
                                if (GlideLoad.needLoad(true)) {
                                    mBitmapTypeRequest
                                            .load(userDo.getUserPhotoUrl())
                                            .placeholder(R.drawable.ic_mine_icon)
                                            .error(R.drawable.ic_mine_icon)
                                            .centerCrop()
                                            .into(new RoundImageViewTarget(img_user));
                                } else {
                                    mBitmapTypeRequest
                                            .load("")
                                            .placeholder(R.drawable.ic_mine_icon)
                                            .error(R.drawable.ic_mine_icon)
                                            .centerCrop()
                                            .into(new RoundImageViewTarget(img_user));
                                }
                                collectInfo();
                                activityInfo();
                            }
                        }
                    });
        } else {
            btn_login.setVisibility(View.VISIBLE);
            atv_user_name.setText("");
            img_user.setImageResource(R.drawable.ic_mine_icon);
            atv_collection_number.setText("0");
            atv_activity_number.setText("0");
        }
    }

    /**
     * 用户状态改变
     */
    @Subscribe
    public void onEventMainThread(UserOperate userOperate) {
        switch (userOperate.getStatus()) {
            default:
                setUserInfo();
                break;
        }
    }

    /**
     * 用户中心数据变化
     */
    @Subscribe
    public void onEventMainThread(MineInfoUpdate mineInfoUpdate) {
        int status = mineInfoUpdate.getStatus() > 10 ?
                mineInfoUpdate.getStatus() / 10 : mineInfoUpdate.getStatus();
        switch (status) {
            case 0:
                fpHistoryCount();
                break;
            case 1:
                collectInfo();
                break;
            case 2:
                activityInfo();
                break;
            default:
                break;
        }
    }

    /**
     * 足迹数量
     */
    private void fpHistoryCount() {
        RxDataBase.fpHistoryCount()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<Integer>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        atv_footprint_number.setText(String.valueOf(integer));
                    }
                });
    }

    /**
     * 收藏数量
     */
    private void collectInfo() {
        RxRequest.collectInfoCount(MineFragment.class)
                .compose(this.<CollectInfoListRo>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new Action1<CollectInfoListRo>() {
                    @Override
                    public void call(CollectInfoListRo collectInfoListRo) {
                        atv_collection_number.setText(String.valueOf(collectInfoListRo.getTotal()));
                    }
                });
    }

    /**
     * 活动数量
     */
    private void activityInfo() {
        UserBookingListApi userBookingListApi = new UserBookingListApi(MineFragment.class,
                UserBookListRo.class, new IResponseListener<UserBookListRo>() {
            @Override
            public void onResponse(UserBookListRo userBookListRo) {
                atv_activity_number.setText(String.valueOf(userBookListRo.getTotal()));
            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        userBookingListApi.setCount(0);
        userBookingListApi.startRequest();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_msg:
                startActivity(new Intent(getActivity(), SysMsgListActivity.class));
                break;
            case R.id.btn_login:
                startActivity(new Intent(getActivity(), LoginActivity.class));
                break;
            case R.id.atv_user_name:
                if (AppConstant.IsLogin) {
                    if ("点击设置".equals(atv_user_name.getText().toString())) {
                        startActivityForResult(new Intent(getActivity(), SettingsNickNameActivity.class),
                                MyProfileActivity.SET_NICK_NAME);
                    } else {
                        startActivity(new Intent(getContext(), MyProfileActivity.class));
                    }
                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
            case R.id.img_user:
                if (AppConstant.IsLogin) {
                    startActivity(new Intent(getContext(), MyProfileActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                baiduEvent("N6_1_Click");
                break;
            case R.id.ll_footprint:
                startActivity(new Intent(getActivity(), FootPrintActivity.class));
                break;
            case R.id.ll_collection:
                startActivity(new Intent(getActivity(), CollectionActivity.class));
                break;
            case R.id.ll_activity:
                startActivity(new Intent(getActivity(), MyActivityActivity.class));
                break;
            case R.id.rl_contact:
                startActivity(new Intent(getActivity(), ContactActivity.class));
                baiduEvent("N5_1_Click");
                break;
            case R.id.rl_loan_calculator:
                startActivity(new Intent(getActivity(), LoanCalcActivity.class));
                baiduEvent("N3_1_Click");
                break;
            case R.id.rl_tax_calculator:
                startActivity(new Intent(getActivity(), TaxCalcActivity.class));
                baiduEvent("N4_1_Click");
                break;
            case R.id.rl_settings_opinion:
                startActivity(new Intent(getActivity(), OpinionActivity.class));
                break;
            case R.id.rl_share:
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_content));
                startActivity(intent);
                baiduEvent("N2_1_Type");
                break;
            case R.id.rl_setting:
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (-1 == resultCode) {
            switch (requestCode) {
                case MyProfileActivity.SET_NICK_NAME:
                    setUserInfo();
                    break;
                default:
                    break;
            }
        }
    }
}
